using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CodeStory.Core;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.UI;
using System.IO;

namespace CodeStory.WebApplication.Modules.Core.Admin
{
	[NavigationPortlet("CodeStory_Core_Admin_CreateModule")]
	public partial class CreateModule : Portlet
	{
		protected override void OnInit(EventArgs e) {
			Load += new EventHandler(CreateModule_Load);
			btnCreate.Click += new EventHandler(ButtonCreate_Click);
			dpdDirectory.SelectedIndexChanged += new EventHandler(DropDownListDirectory_SelectedIndexChanged);
			base.OnInit(e);
		}

		void DropDownListDirectory_SelectedIndexChanged(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			txtDirectory.Text = dpdDirectory.SelectedValue;
		}
		private Guid ModuleID {
			get { 
				string str = Request.QueryString["moduleid"];
				Guid id = Guid.Empty;
				if (!string.IsNullOrEmpty(str)) {
					try {
						id = new Guid(str);
					} catch {
					}
				}
				return id;
			}
		}

		void ButtonCreate_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			ModuleObject m;
			if (ModuleID == Guid.Empty) {
				m = ModuleObject.New();
			} else {
				m = ModuleObject.Read(ModuleID);
			}
			m.ModuleName = txtName.Text;
			m.ModuleDescription = txtDescription.Text;
			m.Author = txtAuthor.Text;
			m.Version = txtVersion.Text;
			m.InstallDirectory = txtDirectory.Text;
			m.Save();
			Response.Redirect(string.Format("~/{0}.portlet.aspx", "CodeStory_Core_Admin_ModuleManager"));
		}

		void CreateModule_Load(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			if (!Page.IsPostBack) {
				BindDirectory();
				if (ModuleID != Guid.Empty) {
					ModuleObject obj = ModuleObject.Read(ModuleID);
					txtName.Text = obj.ModuleName;
					txtDescription.Text = obj.ModuleDescription;
					txtAuthor.Text = obj.Author;
					txtVersion.Text = obj.Version;
					txtDirectory.Text = obj.InstallDirectory;
				}
			}
		}

		private void BindDirectory() {
			string path = Path.Combine(Request.PhysicalApplicationPath, "Skins/default");
			DirectoryInfo di = new DirectoryInfo(path);
			dpdDirectory.DataSource = di.GetDirectories();
			dpdDirectory.DataTextField = "Name";
			dpdDirectory.DataValueField = "Name";
			dpdDirectory.DataBind();
			ListItem item = new ListItem("(--none--)","");
			dpdDirectory.Items.Insert(0, item);
		}
	}
}